// index.js
const AudioManager = require('../../utils/audioManager');
const StorageManager = require('../../utils/storageManager');
const TimerManager = require('../../utils/timerManager');

const AppConstants = {
  MAX_TIME_PICKERS: 5,
  DEFAULT_INTERVAL: 60,
  MAX_RECORD_DURATION: 60000, // 60秒
  FREQUENCY: {
    DAILY: 'daily',
    HOURLY: 'hourly',
    CUSTOM: 'custom',
  }
};

Page({
  data: {
    AppConstants,
    isRecording: false,
    isPlaying: false,
    recordTime: 0,
    audioPath: '',
    frequency: AppConstants.FREQUENCY.DAILY,
    selectedTimes: ['09:00'],
    customInterval: AppConstants.DEFAULT_INTERVAL,
    reminders: []
  },

  onLoad() {
    this.initManagers();
    this.loadReminders();
  },

  onShow() {
    this.loadReminders();
  },


  // 初始化管理器
  initManagers() {
    this.audioManager = new AudioManager();
    this.storageManager = new StorageManager();
    this.timerManager = new TimerManager();
    
    // 初始化录音管理器
    this.audioManager.initRecorder({
      onStart: () => {
        this.setData({ isRecording: true, recordTime: 0 });
        this.updateRecordTime();
      },
      onStop: (res) => {
        this.setData({
          audioPath: res.tempFilePath,
          isRecording: false
        });
      },
      onError: (err) => {
        console.error('录音错误', err);
        wx.showToast({ title: '录音失败', icon: 'error' });
        this.setData({ isRecording: false });
      }
    });

    // 初始化音频播放器
    this.audioManager.initPlayer({
      onPlay: () => {
        this.setData({ isPlaying: true });
      },
      onEnded: () => {
        this.setData({ isPlaying: false });
      },
      onError: (err) => {
        console.error('音频播放错误', err);
        this.setData({ isPlaying: false });
        wx.showToast({ title: '播放失败', icon: 'error' });
      }
    });
  },

  // 切换录音状态
  toggleRecord() {
    if (this.data.isRecording) {
      this.stopRecord();
    } else {
      this.startRecord();
    }
  },

  // 开始录音
  async startRecord() {
    try {
      this.setData({ audioPath: '' });
      await this.audioManager.startRecord({ duration: AppConstants.MAX_RECORD_DURATION });
    } catch (error) {
      console.error('请求录音权限失败', error);
      wx.showModal({
        title: '需要录音权限',
        content: '请在设置中开启录音权限，否则无法使用核心功能。',
        showCancel: false
      });
    }
  },

  // 停止录音
  stopRecord() {
    this.audioManager.stopRecord();
  },

  // 更新录音时间
  updateRecordTime() {
    const timer = setInterval(() => {
      if (!this.audioManager.isRecording) {
        clearInterval(timer);
        return;
      }
      this.setData({
        recordTime: this.audioManager.getRecordTime()
      });
    }, 1000);
  },

  // 播放音频
  playAudio() {
    if (!this.data.audioPath) return;
    this.audioManager.playAudio(this.data.audioPath);
  },

  // 设置频率
  setFrequency(e) {
    const frequency = e.currentTarget.dataset.frequency;
    this.setData({ frequency });
  },

  // 时间选择
  onTimeChange(e) {
    const index = e.currentTarget.dataset.index;
    const selectedTimes = this.data.selectedTimes;
    selectedTimes[index] = e.detail.value;
    this.setData({
      selectedTimes
    });
  },

  // 添加时间选择器
  addTimePicker() {
    const selectedTimes = this.data.selectedTimes;
    if (selectedTimes.length >= AppConstants.MAX_TIME_PICKERS) {
      wx.showToast({ title: `最多添加${AppConstants.MAX_TIME_PICKERS}个时间点`, icon: 'none' });
      return;
    }
    selectedTimes.push('12:00');
    this.setData({
      selectedTimes
    });
  },

  // 移除时间选择器
  removeTimePicker(e) {
    const index = e.currentTarget.dataset.index;
    const selectedTimes = this.data.selectedTimes;
    if (selectedTimes.length <= 1) {
      wx.showToast({ title: '至少保留一个时间点', icon: 'none' });
      return;
    }
    selectedTimes.splice(index, 1);
    this.setData({
      selectedTimes
    });
  },

  // 间隔输入
  onIntervalInput(e) {
    this.setData({
      customInterval: parseInt(e.detail.value) || AppConstants.DEFAULT_INTERVAL
    });
  },

  // 保存提醒
  async saveReminder() {
    if (!this.data.audioPath) {
      wx.showToast({ title: '请先录制音频', icon: 'error' });
      return;
    }

    const { frequency, selectedTimes, customInterval, audioPath } = this.data;

    if (!this.validateReminderInput()) {
      return;
    }

    try {
      const savedPath = await this.storageManager.saveAudioFile(audioPath);
      
      const reminderData = {
        audioPath: savedPath,
        frequency,
        times: frequency === AppConstants.FREQUENCY.DAILY ? selectedTimes : null,
        interval: frequency === AppConstants.FREQUENCY.CUSTOM ? customInterval : null,
        frequencyText: TimerManager.getFrequencyText(frequency, selectedTimes, customInterval)
      };
      
      const newReminder = this.storageManager.addReminder(reminderData);
      
      if (newReminder) {
        // 设置定时器
        this.timerManager.scheduleReminder(newReminder, () => {
          this.playReminderAudio(newReminder.audioPath);
        });
        
        this.loadReminders();
        this.setData({ audioPath: '', recordTime: 0 });
        wx.showToast({ title: '保存成功', icon: 'success' });
      } else {
        throw new Error('保存提醒失败');
      }
    } catch (error) {
      console.error('保存提醒失败', error);
      wx.showToast({ title: '保存失败', icon: 'error' });
    }
  },

  // 验证提醒输入
  validateReminderInput(frequency, selectedTimes, customInterval) {
    if (frequency === 'daily' && selectedTimes.some(time => !time)) {
      wx.showToast({ title: '请选择所有播放时间', icon: 'error' });
      return false;
    }

    if (frequency === 'custom' && !TimerManager.validateInterval(customInterval)) {
      wx.showToast({ title: '请输入有效的间隔时间(1-1440分钟)', icon: 'error' });
      return false;
    }

    return true;
  },

  // 验证提醒输入
  validateReminderInput() {
    const { frequency, selectedTimes, customInterval } = this.data;

    if (frequency === AppConstants.FREQUENCY.DAILY && selectedTimes.length === 0) {
      wx.showToast({ title: '请至少选择一个时间点', icon: 'error' });
      return false;
    }

    if (frequency === AppConstants.FREQUENCY.CUSTOM && (!customInterval || customInterval <= 0)) {
      wx.showToast({ title: '自定义间隔需大于0', icon: 'error' });
      return false;
    }

    return true;
  },

  // 播放提醒音频
  playReminderAudio(audioPath) {
    const audio = wx.createInnerAudioContext();
    audio.src = audioPath;
    audio.play();
    
    // 显示提醒
    wx.showModal({
      title: '语音提醒',
      content: '您的定时提醒时间到了！',
      showCancel: false
    });
  },

  // 加载提醒列表
  loadReminders() {
    const reminders = this.storageManager.getReminders();
    this.setData({ reminders });
    
    // 重新设置所有活跃的提醒
    reminders.filter(r => r.isActive).forEach(reminder => {
      this.timerManager.scheduleReminder(reminder, () => {
        this.playReminderAudio(reminder.audioPath);
      });
    });
  },

  // 切换提醒状态
  toggleReminder(e) {
    const id = parseInt(e.currentTarget.dataset.id);
    const success = this.storageManager.toggleReminderStatus(id);
    
    if (success) {
      const reminders = this.storageManager.getReminders();
      const reminder = reminders.find(r => r.id === id);
      
      if (reminder.isActive) {
        this.timerManager.scheduleReminder(reminder, () => {
          this.playReminderAudio(reminder.audioPath);
        });
      } else {
        this.timerManager.pauseReminder(id);
      }
      
      this.setData({ reminders });
      wx.showToast({
        title: reminder.isActive ? '已启用' : '已暂停',
        icon: 'success'
      });
    }
  },

  // 播放提醒音频
  playReminder(e) {
    const audioPath = e.currentTarget.dataset.path;
    this.audioManager.playAudio(audioPath);
  },

  // 删除提醒
  deleteReminder(e) {
    const id = parseInt(e.currentTarget.dataset.id);
    
    wx.showModal({
      title: '确认删除',
      content: '确定要删除这个提醒吗？',
      success: (res) => {
        if (res.confirm) {
          // 清除定时器
          this.timerManager.clearReminder(id);
          
          // 删除提醒
          const success = this.storageManager.deleteReminder(id);
          
          if (success) {
            this.loadReminders();
            wx.showToast({ title: '删除成功', icon: 'success' });
          }
        }
      }
    });
  },

  onUnload() {
    // 清理资源
    if (this.audioManager) {
      this.audioManager.destroy();
    }
    if (this.timerManager) {
      this.timerManager.clearAll();
    }
  }
});